﻿//▲▼◄►

var GridJSON =
{
    TextBox: "TextBox",
    DatePickerJquery: "DatePickerJquery",
    CheckBox: "CheckBox",
    ComboBox: "ComboBox",
    HiddenField: "Hidden",

    DataBind:
    function GridJSON_DataBind(grid, dataTable,dataSourcesControls) 
    {
        if(document.getElementById(grid.TableId) == null)
        {
            if(dataSourcesControls == null)
                GridJSON.DataBindGrid(grid,dataTable);
            else
                GridJSON.DataBindGrid(grid,dataTable,dataSourcesControls);                  
        }
        else
        {
            GridJSON.DataBindOnlyRows(grid,dataTable);
        }
    },

    DataBindGrid:
    function GridJSON_DataBindGrid(grid, dataTable,dataSourcesControls) 
    {
        //Variables de los controles de las grillas
        var id_ddlShowPag = grid.TableId + "_ddlShowPag";
        var id_txtPageIndex = grid.TableId + "_txtPagIndex";
        var id_hiddenPagIndex = grid.TableId + "_hddPagIndex";
        var id_hiddenOrderBy = grid.TableId + "_hddOrderBy";
        var id_labelTotalRecords = grid.TableId + "_labelTotalRecords";
        var id_labelTotalPages = grid.TableId + "_labelTotalPages";

        if(grid.ButtonsActionRecord == null) grid.ButtonsActionRecord = [];

        var totalRegister = ((grid.ShowPaging == null) ? parseInt(dataTable.length) : parseInt(grid.TotalRecords));
        var totalPages = Math.ceil(totalRegister / ((grid.ChooseShowPaging == null) ? totalRegister : grid.ChooseShowPaging));
        if (totalPages == 0) totalPages = 1;

        var colspanExcel = grid.ButtonsActionRecord.length + 1;

        if(dataSourcesControls == null) dataSourcesControls = [];

        var target = $("#" + grid.Target);

        //Limpio el target
        target.html("");

        //Creo la tabla en forma dinamica
        target.append
        (
            $("<input>", { type: "hidden", id: id_hiddenPagIndex, val: grid.PageIndex }),
            $("<input>", { type: "hidden", id: id_hiddenOrderBy, val: grid.OrderBy }),
            $("<table>", {id: grid.TableId}).addClass("TableGridJSON").css("width",(grid.Width == null) ? "" : grid.Width).append
            (
                //Header Grilla
                $("<tr>", {}).addClass("HeaderGridJSON").append
                (
                    //Si cuenta con paginacion o solo mostrara el total de los registros
                    (grid.ShowPaging == null)
                    ?
                    (
                        $("<td>", { colspan: 2 }).append($("<span>", {id: id_labelTotalRecords,html: totalRegister})," registros")
                    )
                    :
                    (
                        $("<td>", { colspan: 2 }).append
                        (
                            //Combobox Show Count Registered
                            GridJSON.ConstructSelectList(id_ddlShowPag,grid.ShowPaging,grid.ChooseShowPaging,false).change
                            (
                                function () 
                                {
                                    var newShowPaging = $(this).val();
                                    var totalRecords = parseInt($("#" + id_labelTotalRecords).html());

                                    var newTotalPages = Math.ceil(totalRecords / newShowPaging);
                                    if (newTotalPages == 0) newTotalPages = 1;

                                    var txtPagIndex = $("#" + id_txtPageIndex);
                                    var pagIndex = txtPagIndex.val()

                                    if(pagIndex > newTotalPages) pagIndex = newTotalPages;

                                    txtPagIndex.val(pagIndex);
                                    $("#" + id_hiddenPagIndex).val(pagIndex);

                                    GridJSON.ReloadGridJSON(grid);
                                }
                            ),
                            //Show Count Total Registered
                            " de ",  
                            $("<span>", {id: id_labelTotalRecords,html: totalRegister})
                        )
                    ),
                    //Si cuenta con paginacion se pondra los controles de navegacion sino solo el exportar excel
                    (grid.ShowPaging == null)
                    ?
                    (
                        $("<td>", { css: { "text-align": "center" }, colspan: (grid.Fields.length - 2) + colspanExcel }).append
                        (
                            GridJSON.ConstructCellExportToExcel(grid)
                        )
                    )
                    :
                    (
                        $("<td>", { css: { "text-align": "center" }, colspan: (grid.Fields.length - 2) + colspanExcel }).append
                        (
                            //Button for first page
                            $("<span>", 
                            { 
                                html: "&nbsp;|◄◄&nbsp;", title: "Primero", css: { "font-weight": "bold", "cursor": "pointer"},
                                click: 
                                function()
                                {
                                    var pagIndex = 1;

                                    $("#" + id_txtPageIndex).val(pagIndex);
                                    $("#" + id_hiddenPagIndex).val(pagIndex);

                                    GridJSON.ReloadGridJSON(grid);
                                }
                            }),
                            "&nbsp;&nbsp;&nbsp;",
                            //Button for before page
                            $("<span>", 
                            { 
                                html: "&nbsp;◄&nbsp;", title: "Anterior", css: { "font-weight": "bold", "cursor": "pointer"}, 
                                click: 
                                function()
                                {
                                    var txtPagIndex = $("#" + id_txtPageIndex);
                                    var pagIndex = parseInt(txtPagIndex.val());

                                    if(pagIndex==1) return;

                                    pagIndex--;

                                    txtPagIndex.val(pagIndex);
                                    $("#" + id_hiddenPagIndex).val(pagIndex);

                                    GridJSON.ReloadGridJSON(grid);
                                }
                            }),
                            "&nbsp;&nbsp;&nbsp;",
                            "Página",
                            "&nbsp;&nbsp;&nbsp;",
                            //Text input for page index
                            $("<input >",
                            {
                                id: id_txtPageIndex,
                                maxlength: 5, type: "text", val: ((grid.PageIndex > totalPages) ? totalPages : grid.PageIndex),
                                blur: function () { $(this).val($("#" + id_hiddenPagIndex).val()) },
                                keypress:
                                function (event) 
                                {
                                    if (!(event.which == 13)) return;
                                
                                    var regex = new RegExp("^\\d*$","i"); 

                                    var pag = $(this).val();
                                    var pagLast = parseInt($("#" + id_labelTotalPages).html());

                                    if(!regex.test(pag)) pag = "0";

                                    pag = parseInt(pag);

                                    if(!(pag > 0 && pag <= pagLast))
                                    {
                                        $(this).val($("#" + id_hiddenPagIndex).val());
                                        return;
                                    }

                                    $("#" + id_hiddenPagIndex).val(pag);

                                    GridJSON.ReloadGridJSON(grid);
                                }
                            }),
                            "&nbsp;&nbsp;&nbsp;",
                            "de",
                            "&nbsp;&nbsp;&nbsp;",
                            $("<span>", {id: id_labelTotalPages,html: totalPages}),
                            "&nbsp;&nbsp;&nbsp;",
                            //Button for after page
                            $("<span>", 
                            { 
                                html: "&nbsp;►&nbsp;", title: "Siguiente", css: { "font-weight": "bold", "cursor": "pointer"},
                                click: 
                                function()
                                {
                                    var txtPagIndex = $("#" + id_txtPageIndex);

                                    var pagIndex = parseInt(txtPagIndex.val());
                                    var pagLast = parseInt($("#" + id_labelTotalPages).html());

                                    if(pagIndex==pagLast) return;

                                    pagIndex++;

                                    txtPagIndex.val(pagIndex);
                                    $("#" + id_hiddenPagIndex).val(pagIndex);

                                    GridJSON.ReloadGridJSON(grid);
                                }
                            }),
                            "&nbsp;&nbsp;&nbsp;",
                            $("<span>", 
                            { 
                                html: "&nbsp;►►|&nbsp;", title: "Ultimo", css: { "font-weight": "bold", "cursor": "pointer"} ,
                                click: 
                                function()
                                {
                                    var pagLast = $("#" + id_labelTotalPages).html();

                                    $("#" + id_txtPageIndex).val(pagLast);
                                    $("#" + id_hiddenPagIndex).val(pagLast);

                                    GridJSON.ReloadGridJSON(grid);
                                }
                            }),
                            GridJSON.ConstructCellExportToExcel(grid)
                        )
                    )
                ),
                //Cabeceras de la grilla
                $("<tr>", { id: grid.TableId + "_headerRow"}).append
                (
                    $("<th>", {}).addClass("ColumnSelect"),
                    $.map
                    (
                        grid.Fields,
                        function (field) 
                        {
                            if(grid.OrderBy == null)
                                return $("<th>",{ html: field.Header }).css("width",(field.Width == null) ? "" : field.Width);
                            else
                                return $("<th>",{ html: field.Header }).css("width",(field.Width == null) ? "" : field.Width).append
                                (
                                    //Button Order By Desc ▼
                                    $("<span>", 
                                    { 
                                        html: "&nbsp;▼", css: { "float": "right" , "cursor": "pointer"} ,
                                        click: 
                                        function()
                                        {
                                            var orderBy = (field.OrderBy == null) ? field.DataField : field.OrderBy;
                                            orderBy = orderBy + " Desc";
                                            $("#" + id_hiddenOrderBy).val(orderBy);   

                                            GridJSON.ReloadGridJSON(grid);
                                        }
                                    }),
                                    //Button Order By Asc ▲
                                    $("<span>", 
                                    { 
                                        html: "▲", css: { "float": "right" , "cursor": "pointer"},
                                        click: 
                                        function()
                                        {
                                            var orderBy = (field.OrderBy == null) ? field.DataField : field.OrderBy;
                                            orderBy = orderBy + " Asc";
                                            $("#" + id_hiddenOrderBy).val(orderBy);   

                                            GridJSON.ReloadGridJSON(grid);
                                        }
                                    })
                                );
                        }
                    ),
                    GridJSON.ConstructAddButtonRecordGrid(grid)
                ),
                //Fila de busqueda si es que hay
                GridJSON.ConstructRowSearchRecordGrid(grid,dataSourcesControls),
                //Filas de la consulta del datatable
                GridJSON.ConstructRowsResultGrid(grid,dataTable)
            )
        );
    },

    DataBindOnlyRows:
    function GridJSON_DataBindOnlyRows(grid, dataTable) 
    {
        var id_labelTotalRecords = grid.TableId + "_labelTotalRecords";
        var id_labelTotalPages = grid.TableId + "_labelTotalPages";

        var totalRegister = ((grid.ShowPaging == null) ? parseInt(dataTable.length) : parseInt(grid.TotalRecords));
        var totalPages = Math.ceil(totalRegister / ((grid.ChooseShowPaging == null) ? totalRegister : grid.ChooseShowPaging));
        if (totalPages == 0) totalPages = 1;

        //Si ya existe la grilla solo creo los registros
        $("#" + grid.TableId + " tbody tr").filter("[id^=" + grid.TableId + "_row]").remove();

        GridJSON.OnOffButtonsRecordGrid(grid.TableId,true);

        $("#" + grid.TableId).append
        (
            GridJSON.ConstructRowsResultGrid(grid,dataTable)
        );

        $("#" + id_labelTotalRecords).html(totalRegister);

        if(grid.ShowPaging != null) $("#" + id_labelTotalPages).html(totalPages);
    },

    ConstructCellExportToExcel:
    function GridJSON_ConstructCellExportToExcel(grid) 
    {
        return (
            (grid.FunctionExportToExcel == null) ?
            "" :
            $("<img>", 
            {
                title: "Exportar a Excel", 
                click: 
                function()
                {
                    if(grid.RecordSearch==null)
                        grid.FunctionExportToExcel();
                    else
                    {
                        var search = {};
                        search[grid.PrimaryKey] = null;

                        var recordSearch = GridJSON.GetNewRecord(grid,search,false,grid.TableId + "_searchRow");

                        grid.FunctionExportToExcel(recordSearch);    
                    }
                }
            }).addClass("IconExcel")
        );
    },

    ConstructRowsResultGrid:
    function GridJSON_ConstructRowsResultGrid(grid,dataTable) 
    {
        var flagAlternate = false;

        return  $.map
        (
            dataTable,
            function (dataItem) 
            {
                var classRowGrid = (!flagAlternate ? "rowGridJSON" : "rowGridJSONAlter");

                flagAlternate = !flagAlternate;

                return GridJSON.ConstructRowRecordGrid(grid,dataItem,classRowGrid).append
                (
                    $("<td>", { html: "►" }).addClass("ColumnSelect"),
                    GridJSON.ConstructRecordGrid(grid,dataItem),
                    GridJSON.ConstructButtonsRecordGrid(grid, dataItem) 
                );
            }
        );
    },

    ReloadGridJSON:
    function GridJSON_ReloadGridJSON(grid) 
    {
        var recordSearch = {};
        recordSearch[grid.PrimaryKey] = null;

        if(grid.RecordSearch != null) recordSearch = GridJSON.GetNewRecord(grid,recordSearch,false,grid.TableId + "_searchRow");

        var orderBy = $("#" + grid.TableId + "_hddOrderBy").val();
        var showPagging = $("#" + grid.TableId + "_ddlShowPag").val();
        var pageIndex = $("#" + grid.TableId + "_hddPagIndex").val();

        if(grid.RecordSearch != null) //Si tiene busqueda
        {
            //Si hubo algun problema con la busqueda
            if(recordSearch == null) return;

            if(grid.OrderBy == null && grid.ShowPaging == null) //Si solo tiene busqueda
                grid.FunctionLoadGrid(recordSearch);
            else if(grid.OrderBy != null && grid.ShowPaging == null) // Si tiene order by pero no tiene paginacion
                grid.FunctionLoadGrid(recordSearch,orderBy);
            else if(grid.ShowPaging != null && grid.OrderBy == null) // Si tiene paginacion pero no Order by
                grid.FunctionLoadGrid(recordSearch,showPagging,pageIndex);
            else //Si tiene los tres
                grid.FunctionLoadGrid(recordSearch,orderBy,showPagging,pageIndex);       
        }
        else if(grid.OrderBy != null)
        {
            if(grid.RecordSearch == null && grid.ShowPaging == null) //Si solo tiene Order By
                grid.FunctionLoadGrid(orderBy);
            else if(grid.RecordSearch != null && grid.ShowPaging == null) // Si tiene busqueda pero no tiene paginacion
                grid.FunctionLoadGrid(recordSearch,orderBy);
            else if(grid.ShowPaging != null && grid.RecordSearch == null) // Si tiene paginacion pero no busqueda
                grid.FunctionLoadGrid(orderBy,showPagging,pageIndex);
            else //Si tiene los tres
                grid.FunctionLoadGrid(recordSearch,orderBy,showPagging,pageIndex);       
        }
        else if(grid.ShowPaging != null)
        {
            if(grid.RecordSearch == null && grid.OrderBy == null) //Si solo tiene paginacion
                grid.FunctionLoadGrid(orderBy);
            else if(grid.RecordSearch != null && grid.OrderBy == null) // Si tiene busqueda pero no tiene Order BY
                grid.FunctionLoadGrid(recordSearch,orderBy);
            else if(grid.OrderBy != null && grid.RecordSearch == null) // Si tiene Order By pero no tiene Busqueda
                grid.FunctionLoadGrid(recordSearch,showPagging,pageIndex);
            else //Si tiene los tres
                grid.FunctionLoadGrid(recordSearch,orderBy,showPagging,pageIndex);       
        }
        else //Si el grid no tiene ni busqueda, ni order by, ni paginacion
        {
            grid.FunctionLoadGrid();
        }    
    },

    ConstructRowSearchRecordGrid:
    function GridJSON_ConstructRowSearchRecordGrid(grid,dataSourcesControls) 
    {
        if(grid.RecordSearch==null) return "";

        var record = grid.RecordSearch;
        record[grid.PrimaryKey] = "";

        var prefixRow = grid.TableId + "_searchRow";

        var buttonsSearch = 
        [
            {
                styleCss: "IconRecordSearch",
                toolTip: "Buscar",
                functionAction:
                function(id)
                {
                    var id_txtPageIndex = grid.TableId + "_txtPagIndex";
                    var id_hiddenPagIndex = grid.TableId + "_hddPagIndex";

                    $("#" + id_txtPageIndex).val(1);
                    $("#" + id_hiddenPagIndex).val(1);

                    GridJSON.ReloadGridJSON(grid);
                }
            }
        ];

        return $("<tr>",{ id : prefixRow}).addClass("RowSearch").append
        (
            $("<th>", { html: "►"}).addClass("ColumnSelect"),
            $.map
            (
                grid.Fields,
                function (field) 
                {   
                    if(record[field.DataFieldEdit] != null)
                        return GridJSON.ConstructControlEditGrid(grid,field,record,dataSourcesControls,"<th>");
                    else             
                        return $("<th>", {});
                }
            ),
            GridJSON.ConstructButtonsRecordGrid(grid,record,buttonsSearch,"<th>")
        );
    },

    EditRecordGrid:
    function GridJSON_EditRecordGrid(grid, record,dataSources) 
    {
        if(record == null) record = {};

        if(record[grid.PrimaryKey] == null) record[grid.PrimaryKey] = "";

        if(record[grid.PrimaryKey] == "") record[grid.PrimaryKey] = "0";

        if(dataSources == null) dataSources = [];

        GridJSON.OnOffButtonsRecordGrid(grid.TableId,false);

        var rowEdit = $("#" + grid.TableId + "_row" + record[grid.PrimaryKey]);

        rowEdit.html("");

        var buttonsEdit =
        [
            { 
                styleCss: "IconRecordConfirm", 
                toolTip: "Confirmar",
                functionAction: 
                function()
                {
                    var newRecord = GridJSON.GetNewRecord(grid,record);

                    if(newRecord == null) return;

                    grid.FunctionSaveRecord(newRecord);
                } 
            },
            { 
                styleCss: "IconRecordCancel", 
                toolTip: "Cancelar",
                functionAction: 
                function()
                {
                    if(parseInt(record[grid.PrimaryKey]) > 0)
                        GridJSON.ReconstructRecordGrid(grid,record);
                    else
                    {
                        rowEdit.remove();

                        GridJSON.OnOffButtonsRecordGrid(grid.TableId,true);
                    }
                } 
            }
        ];

        rowEdit.append
        (
            $("<td>", { html: "►" }).addClass("ColumnSelect"),
            GridJSON.ConstructRecordEditGrid(grid,record,dataSources),
            GridJSON.ConstructButtonsRecordGrid(grid,record,buttonsEdit)
        );
    },

    DeleteRecordGrid:
    function GridJSON_DeleteRecordGrid(grid, idRecord) 
    {
        var rowEdit = $("#" + grid.TableId + "_row" + idRecord);
        var labelTotalRecords = $("#" + grid.TableId + "_labelTotalRecords");

        rowEdit.remove();

        var totalRecords = parseInt(labelTotalRecords.html());
        totalRecords--;

        labelTotalRecords.html(totalRecords);
    },

    GetNewRecord:
    function GridJSON_GetNewRecord(grid, record,validateOn,rowPrefix) 
    {
        if(validateOn == null) validateOn = true;

        if(rowPrefix == null) rowPrefix = grid.TableId + "_row";

        if(record[grid.PrimaryKey] == null) record[grid.PrimaryKey] = "";

        var isSearch = (rowPrefix.indexOf("search")>0);

        var rowEdit = $("#" + rowPrefix + record[grid.PrimaryKey]);
        var prefixCtlEdit = "#" + grid.TableId + "_ctlEdit" + record[grid.PrimaryKey] + "_";
        var validateAll = true;

        var newRecord = { };

        newRecord[grid.PrimaryKey] = (record[grid.PrimaryKey] == "") ? "0" : record[grid.PrimaryKey];

        $.each
        ( 
            grid.Fields, 
            function(index,field) 
            {
                var dataField = (field.DataFieldEdit == null) ? field.DataField : field.DataFieldEdit;

                //Si es busqueda y no tiene control de busqueda
                if(isSearch) 
                    if(grid.RecordSearch[dataField] == null)
                        return;

                var validate = true;

                if(field.Required == null) field.Required = false;

                var ctrl = rowEdit.find(prefixCtlEdit + dataField);

                var value = null;
                
                if(field.DataFieldEdit == null)
                {
                    if(ctrl.attr("type") == "checkbox")
                        value = ctrl.is(":checked");
                    else
                        value = ctrl.html();
                }
                else
                {
                    var typeControl = (field.ControlEdit == null) ? "" : field.ControlEdit.toUpperCase();

                    switch(typeControl)
                    {
                        case "CHECKBOX":
                            value = ctrl.is(":checked");
                            break;
                        case "HIDDEN":
                            var cellHtml = $(ctrl).parents("td:first").html();
                            newRecord[field.DataField] = cellHtml.split("<input")[0].trim();
                            value = ctrl.val();
                            break;
                        case "COMBOBOX":
                            newRecord[field.DataField] = ctrl.find("option:selected").text();
                            value = ctrl.val();
                            break;        
                        default:
                            value = ctrl.val();
                            break;
                    }
                }

                if(validateOn && field.Required && value == "") validate = false;

                if(value != "" && validate && field.DataFieldEdit != null && field.RegularExpression != null)
                {
                    var regex = new RegExp(field.RegularExpression,"i");

                    if(!regex.test(value)) 
                        validate = false;
                }

                var classCtrl = (field.ControlCss == null) ? "" : field.ControlCss;

                ctrl.removeClass();
                ctrl.addClass(classCtrl); 

                if(!validate) 
                {
                    validateAll = false;
                    ctrl.addClass("RequiredValidateGridJSON"); 
                }
                
                newRecord[dataField] = value;
            }
        );
        
        if(validateAll)
            return newRecord;
        else
            return null;
    },

    ConstructRecordEditGrid:
    function GridJSON_ConstructRecordEditGrid(grid, record,dataSources) 
    {
        return $.map
        (
            grid.Fields,
            function (field) 
            {
                return GridJSON.ConstructControlEditGrid(grid,field,record,dataSources);
            }
        );        
    },

    ConstructControlEditGrid:
    function GridJSON_ConstructControlEditGrid(grid,field,record,dataSources,tag) 
    {
        var prefix = grid.TableId + "_ctlEdit" + record[grid.PrimaryKey] + "_";

        if(tag == null) tag = "<td>";

        var typeControl = null;

        if(field.DataFieldEdit == null) 
            typeCotrol = "";
        else
            typeControl = (field.ControlEdit == null) ? "" : field.ControlEdit.toUpperCase();

        var control = null;

        switch(typeControl)
        {
            case "TEXTBOX":
                control = $("<input>",
                {
                    id: prefix + field.DataFieldEdit,
                    type: "text",
                    val: record[field.DataFieldEdit],
                    maxlength : field.MaxLength
                });
                break;
            case "CHECKBOX":
                control = $("<input>",
                {
                    id: prefix + field.DataFieldEdit,
                    type: "checkbox",
                    checked : record[field.DataFieldEdit]
                });
                break;
            case "COMBOBOX":
                control = GridJSON.ConstructSelectList
                (
                    prefix + field.DataFieldEdit,
                    GridJSON.DataSourceToControlEdit(field.DataFieldEdit,dataSources),
                    record[field.DataFieldEdit]
                );
                break;                
            case "DATEPICKERJQUERY":
                control = $("<input>",
                {
                    id: prefix + field.DataFieldEdit,
                    type: "text", 
                    val: record[field.DataFieldEdit]
                }).datepicker({changeMonth: true,changeYear: true});        
                break;
            case "HIDDEN":
                control = $("<input>",
                {
                    id: prefix + field.DataFieldEdit,
                    type: "hidden", 
                    val: record[field.DataFieldEdit]
                });        
                break;
            default:
                return GridJSON.ConstructCellRecordGrid(record,field,tag,prefix + field.DataField);
        }

        control.addClass((field.ControlCss == null) ? "" : field.ControlCss);

        control.keypress
        (
            function (event) 
            {
                if (!(event.which == 13)) return;
             
                if(record[grid.PrimaryKey] == "")
                    $("#" + grid.TableId + " tbody #" + grid.TableId + "_searchRow .IconRecordSearch").click();
                else
                    $("#" + grid.TableId + " tbody #" + grid.TableId + "_row" + record[grid.PrimaryKey] + " .IconRecordConfirm").click();
            }
        );        

        return $(tag, { html : ((typeControl == "HIDDEN") ? record[field.DataField] : "") }).addClass((field.StyleCss == null) ? "" : field.StyleCss).append(control);
    },

    SearchRecordsGridJSON:
    function GridJSON_SearchRecordsGridJSON(grid) 
    {
        var boton = $("#" + grid.TableId + " tbody #" + grid.TableId + "_searchRow .IconRecordSearch");
        
        if(boton.css("display") == "none") GridJSON.OnOffButtonsRecordGrid(grid.TableId,true);
        
        boton.click();
    },

    AddRecordGridJSON:
    function GridJSON_AddRecordGridJSON(grid) 
    {
        var boton = $("#" + grid.TableId + " tbody #" + grid.TableId + "_headerRow .IconRecordAdd");
        
        if(boton.css("display") == "none") return;
        
        boton.click();
    },

    ConstructSelectList:
    function GridJSON_ConstructSelectList(idControl,dataSource,valSelected,firstSelect) 
    {   
        if(firstSelect == null) firstSelect = true;

        var list = $("<select>",{ id: idControl });

        if(firstSelect)
            list.append($("<option>",{ value: "", text: "[Seleccionar]" }));

        list.append
        (
            $.map
            (
                dataSource,
                function (item) 
                {
                    var valor = null;
                    var texto = null;

                    if(item.Key == null) 
                    {
                        var valor = item;
                        var texto = item;
                    }
                    else
                    {
                        var valor =  item.Key;
                        var texto = item.Value;
                    }

                    return $("<option>", { value: valor, text: texto });
                }
            )
        );

        if(valSelected != null) list.val(valSelected);

        return list;
    },

    DataSourceToControlEdit:
    function GridJSON_DataSourceToControlEdit(dataFieldEdit,dataSources) 
    {   
        dataFieldEdit = dataFieldEdit.toLowerCase();

        var dataSource = [];

        $.each
        ( 
            dataSources, 
            function(index,data) 
            {
                if(data.DataFieldEdit.toLowerCase() == dataFieldEdit)
                {
                    dataSource = data.DataSource;
                    return;
                }
            }
        );

        return dataSource;
    },

    GetTypeObject:
    function GridJSON_GetTypeObject (val) 
    {
        if (typeof val === 'undefined') return 'undefined';
        if (typeof val === 'object' && !val) return 'null';
        return ({}).toString.call(val).match(/\s([a-zA-Z]+)/)[1].toLowerCase();
    },

    ConstructRecordGrid:
    function GridJSON_ConstructRecordGrid(grid, record) 
    {
        return $.map
        (
            grid.Fields,
            function (field) 
            {
                return GridJSON.ConstructCellRecordGrid(record,field);
            }
        );        
    },

    ConstructCellRecordGrid:
    function GridJSON_ConstructCellRecordGrid(record,field,tag,id) 
    {
        if(tag==null) tag = "<td>";
        if(id==null) id = "";

        var cell = null;

        if(GridJSON.GetTypeObject(record[field.DataField]) == "boolean" && tag == "<td>")
            cell = $(tag, { }).append($("<input>", { "id": id, type: "checkbox", checked: record[field.DataField],disabled:true }));
        else
            cell = $(tag, { "id": id, html: record[field.DataField] });

        cell.addClass((field.StyleCss == null) ? "" : field.StyleCss);
                    
        return cell;
    },

    ReconstructRecordGrid:
    function GridJSON_ReconstructRecordGrid(grid, record,newRecord) 
    {
        if(newRecord == null) newRecord = false;

        var rowEdit = null;
    
        //Si no acaba de agregar un registro adicional
        if(!newRecord) 
            rowEdit = $("#" + grid.TableId + "_row" + record[grid.PrimaryKey]);    
        else
            rowEdit = $("#" + grid.TableId + "_row0");
         
        rowEdit.html("");

        rowEdit.append
        (
            $("<td>", { html: "►" }).addClass("ColumnSelect"),
            GridJSON.ConstructRecordGrid(grid,record),
            GridJSON.ConstructButtonsRecordGrid(grid,record)
        );

        rowEdit.attr("id",grid.TableId + "_row" + record[grid.PrimaryKey]);

        GridJSON.OnOffButtonsRecordGrid(grid.TableId,true);
    },

    OnOffButtonsRecordGrid:
    function GridJSON_OnOffButtonsRecordGrid(table,onOff) 
    {
        if(onOff)
        {
            $("#" + table + " tbody tr img").show();
            $("#" + table + "_searchRow").show();
        }
        else
        {
            $("#" + table + " tbody tr img").hide();
            $("#" + table + "_searchRow").hide();
        }
    },

    ConstructButtonsRecordGrid:
    function GridJSON_ConstructButtonsRecordGrid(grid, record,buttons,tag) 
    {
        if(grid.ButtonsActionRecord == null) grid.ButtonsActionRecord = [];

        if(buttons == null) buttons = grid.ButtonsActionRecord;
        if(tag == null) tag = "<td>";

        var capacity = grid.ButtonsActionRecord.length;

        if(capacity == 0 && !(grid.FunctionAddRecord == null)) capacity = 1;

        if(buttons.length < capacity)
        {
            var longitud = (capacity-buttons.length); 

            for(var i=0;i<longitud;i++)
                buttons.push({ styleCss: "", toolTip: "",functionAction: function(id){} });
        }

        return $.map
        (
            buttons,
            function (button) 
            {
                return $(tag,{ css: { width: 15} }).append
                (
                    $("<img>", 
                    {
                        title: button.toolTip, 
                        click: function(){ button.functionAction(record[grid.PrimaryKey]); }
                    }).addClass(button.styleCss)
                );
            }
        );
    },

    ConstructAddButtonRecordGrid:
    function GridJSON_ConstructAddButtonRecordGrid(grid) 
    {
        if(grid.FunctionAddRecord == null) return GridJSON.ConstructButtonsRecordGrid(grid,{},[],"<th>");

        var record = {};

        record[grid.PrimaryKey] = "0";

        var buttons = 
        [
            {
                styleCss: "IconRecordAdd",
                toolTip: "Agregar",
                functionAction:
                function(id)
                { 
                    var countRow = $("#" + grid.TableId + " tbody tr").filter("[id^=" + grid.TableId + "_row]").length;

                    var classRowGrid = ((countRow % 2) == 1) ? "rowGridJSON" : "rowGridJSONAlter";
                  
                    var idSearch = grid.TableId + "_searchRow";
                    var header = null;

                    if(document.getElementById(idSearch) == null)
                        header = $("#" + grid.TableId + "_headerRow");
                    else
                        header = $("#" + idSearch);

                    header.after
                    (
                        GridJSON.ConstructRowRecordGrid(grid,record,classRowGrid)
                    );

                    grid.FunctionAddRecord(null);
                }
            }
        ];

        return GridJSON.ConstructButtonsRecordGrid(grid,record,buttons,"<th>");
    },

    ConstructRowRecordGrid:
    function GridJSON_ConstructRowRecordGrid(grid,record,classRowGrid) 
    {
        return $("<tr>",
        { 
            id : grid.TableId + "_row" + record[grid.PrimaryKey],
            mouseover: function () { $(this).removeClass(classRowGrid); $(this).addClass("rowGridSelect"); },
            mouseleave: function () { $(this).removeClass("rowGridSelect"); $(this).addClass(classRowGrid); }
        }).addClass(classRowGrid);
    }
};